//
//  ScanLanTableViewController.m
//  Wifi
//
//  Created by srulos on 2017/6/15.
//  Copyright © 2017年 srulos. All rights reserved.
//

#import "ScanLanTableViewController.h"
#import "ScanLAN.h"
#import "WifiHeader.h"
#import "XHRadarView.h"

@interface ScanLanTableViewController ()<ScanLANDelegate>
{
    NSMutableArray * m_arrayConnectedDevices;
    ScanLAN * m_scanLan;
    XHRadarView * m_XHRadarView;
}
@end

@implementation ScanLanTableViewController
- (void)viewWillAppear:(BOOL)animated{
    [self.navigationController.navigationBar setHidden:NO];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = K_NSLOCAL(@"ScanOthers");
    
    m_arrayConnectedDevices = [[NSMutableArray alloc]init];
    m_scanLan = [[ScanLAN alloc]initWithDelegate:self];
    
    [m_scanLan startScan];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [m_scanLan stopScan];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return m_arrayConnectedDevices.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"reuseIdentifier"];
    }
    
    Device * device = [m_arrayConnectedDevices objectAtIndex:indexPath.row];
    
    cell.textLabel.text = device.name;
    cell.detailTextLabel.text = device.address;
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (m_XHRadarView == nil) {
        m_XHRadarView = [[XHRadarView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width)];
        m_XHRadarView.radius = self.view.frame.size.width / 2 - 50;
        m_XHRadarView.backgroundColor = MAIN_COLOR;
        [m_XHRadarView scan];
    }
    
    return m_XHRadarView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return self.view.frame.size.width;
}

#pragma mark scan lan delegate
- (void)scanLANDidFindNewAdrress:(NSString *)address havingHostName:(NSString *)hostName
{
    Device * device = [[Device alloc]init];
    device.name = hostName;
    device.address = address;
    
    [m_arrayConnectedDevices addObject:device];
    [self.tableView reloadData];
    
    [m_XHRadarView randomPoint];
}

- (void)scanLANDidFinishScanning
{
    NSString * message = [NSString stringWithFormat:@"扫描完成！共计%ld个设备连接了当前热点！",m_arrayConnectedDevices.count];
    ALERT_VIEW(nil, message);
}

@end
